package com.example.lesson

import com.example.core.http.EntityCallback
import com.example.core.http.HttpClient
import com.example.core.utils.Utils
import com.example.lesson.entity.Lesson
import com.google.gson.reflect.TypeToken
import kotlin.contracts.contract

/**
 * @author LongMa.
 * @date 2021/2/6
 */
class LessonPresenter(private var activity: LessonActivity) {

    companion object {
        val LESSON_PATH = "lessons"
    }

    private var lessons: List<Lesson> = ArrayList<Lesson>()

    private val type = object : TypeToken<List<Lesson>>() {}.type

    fun fetchData() {
        HttpClient.get(LESSON_PATH, type, object : EntityCallback<ArrayList<Lesson>> {
            override fun onSuccess(lessons: ArrayList<Lesson>) {
                this@LessonPresenter.lessons = lessons
                activity.runOnUiThread { activity.showResult(lessons) }
            }

            override fun onFailure(message: String?) {
                activity.run { Utils.toast(message) }
            }
        })
    }

    fun showPlayback() {
        activity.showResult(lessons.filter {
            it.getState() == Lesson.State.PLAYBACK
        })

    }

}